package com.ts.api.module.match.market.internal.executor.handler;

import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.module.api.convert.core.http.client.ApiHttpMessage;
import com.ts.api.module.api.convert.market.http.ApiConsumerMarketHttpHandler;
import com.ts.api.module.api.entity.ApiUserRequest;
import com.ts.api.module.channel.entity.ChannelRequest;
import com.ts.api.module.channel.entity.po.ChannelMarketPO;
import com.ts.api.module.channel.entity.po.ChannelUserFormFieldPO;
import com.ts.api.module.channel.entity.po.ChannelUserRegisterPO;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteDataExchangeResult;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteFederateResult;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteTask;
import com.ts.api.module.match.market.internal.wrapper.MarketDataExchangeWrapper;
import com.ts.api.module.match.market.internal.wrapper.MarketFederateWrapper;
import com.ts.api.module.match.market.internal.wrapper.context.MarketDataExchangeWrapperContext;
import com.ts.api.module.match.market.internal.wrapper.context.MarketFederateWrapperContext;
import com.ts.api.module.match.market.internal.wrapper.model.MarketDataExchange;
import com.ts.api.module.match.market.internal.wrapper.model.MarketFederate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Callable;

/**
 *  贷超-执行器
 *
 *  @author Pan
 */
@Component
public class MarketExecutorTaskHandler {

    @Autowired
    private MarketDataExchangeWrapperContext marketDataExchangeWrapperContext;
    @Autowired
    private MarketFederateWrapperContext marketFederateWrapperContext;
    @Autowired
    private ApiConsumerMarketHttpHandler apiConsumerMarketHttpHandler;

    /**
     *  执行贷超撞库匹配
     *
     *  @author Pan
     *  @param  marketExecuteTask   执行任务实体
     *  @return List
     */
    public Callable<MarketExecuteDataExchangeResult> submitDataExchange(MarketExecuteTask marketExecuteTask) {
        return () -> dataExchangeTask(marketExecuteTask);
    }

    /**
     *  执行贷超联登
     *
     *  @author Pan
     *  @param  marketExecuteTask   执行任务实体
     *  @return List
     */
    public Callable<MarketExecuteFederateResult> submitFederate(MarketExecuteTask marketExecuteTask) {
        return () -> federateTask(marketExecuteTask);
    }

    /**
     *  执行贷超撞库/联登匹配
     *
     *  @author Pan
     *  @param  marketExecuteTask   执行任务实体
     *  @return List
     */
    public Callable<MarketExecuteFederateResult> submitUnion(MarketExecuteTask marketExecuteTask) {
        return () -> {
            ChannelMarketPO channelMarket = marketExecuteTask.getChannelMarket();

            //  撞库任务
            MarketExecuteDataExchangeResult marketExecuteDataExchangeResult = dataExchangeTask(marketExecuteTask);
            //  撞库返回失败不进行联登
            Boolean hasSuc = marketExecuteDataExchangeResult.getHasSuc();
            if (!hasSuc) {
                MarketExecuteFederateResult marketExecuteFederateResult = new MarketExecuteFederateResult();
                marketExecuteFederateResult.setChannelMarket(channelMarket);
                marketExecuteFederateResult.setHasSuc(false);
                return marketExecuteFederateResult;
            }
            //  联登
            return federateTask(marketExecuteTask);
        };
    }

    /**
     *  贷超撞库任务
     *
     *  @author Pan
     *  @param  marketExecuteTask   执行任务实体
     *  @return Callable
     */
    public MarketExecuteDataExchangeResult dataExchangeTask(MarketExecuteTask marketExecuteTask) {
        ChannelMarketPO channelMarket = marketExecuteTask.getChannelMarket();
        String apiDataExchangeUrl = channelMarket.getApiDataExchangeUrl();
        String apiFederateLoginUrl = channelMarket.getApiFederateUrl();

        //  构建返回响应
        MarketExecuteDataExchangeResult marketExecuteDataExchangeResult = new MarketExecuteDataExchangeResult();
        marketExecuteDataExchangeResult.setChannelMarket(channelMarket);

        //  撞库及联登同时地址不存在,视为普通贷超
        if (ValidParam.isEmpty(apiDataExchangeUrl) && ValidParam.isEmpty(apiFederateLoginUrl)) {
            marketExecuteDataExchangeResult.setHasSuc(true);
            return marketExecuteDataExchangeResult;
        }

        //  不存在撞库请求,只存在联登地址返回撞库请求成功
        if (ValidParam.isEmpty(apiDataExchangeUrl) && ValidParam.isNotEmpty(apiFederateLoginUrl)) {
            marketExecuteDataExchangeResult.setHasSuc(true);
            return marketExecuteDataExchangeResult;
        }

        ChannelRequest channelRequest = marketExecuteTask.getChannelRequest();
        ChannelUserRegisterPO channelUserRegisterPO = marketExecuteTask.getChannelUserRegisterPO();
        List<ChannelUserFormFieldPO> channelUserFormPO = marketExecuteTask.getChannelUserFormPO();

        //  获取撞库包装类
        MarketDataExchange marketDataExchange = MarketDataExchange.of(channelUserRegisterPO, channelUserFormPO, channelRequest.getIp());
        MarketDataExchangeWrapper dataExchangeWrapper = marketDataExchangeWrapperContext.getContext(channelMarket.getApiDataExchangeType());
        ApiUserRequest apiUserRequest = dataExchangeWrapper.wrap(marketDataExchange);
        apiUserRequest.setReqId(ClassConvertUtils.toStr(marketExecuteTask.getReqId()));

        //  发送撞库流程
        ApiHttpMessage apiHttpMessage = apiConsumerMarketHttpHandler.sendDataExchange(channelMarket, apiUserRequest, marketExecuteTask.getHttpTimeout());

        marketExecuteDataExchangeResult.setHasSuc(apiHttpMessage.hasSuc());
        return marketExecuteDataExchangeResult;
    }

    /**
     *  贷超联登任务
     *
     *  @author Pan
     *  @param  marketExecuteTask   执行任务实体
     *  @return Callable
     */
    public MarketExecuteFederateResult federateTask(MarketExecuteTask marketExecuteTask) {
        ChannelMarketPO channelMarket = marketExecuteTask.getChannelMarket();
        ChannelUserRegisterPO channelUserRegisterPO = marketExecuteTask.getChannelUserRegisterPO();
        List<ChannelUserFormFieldPO> listUserForm = marketExecuteTask.getChannelUserFormPO();

        //  构建返回响应
        MarketExecuteFederateResult marketExecuteFederateResult = new MarketExecuteFederateResult();
        marketExecuteFederateResult.setChannelMarket(channelMarket);

        //  不存在联登链接返回默认链接
        if (ValidParam.isEmpty(channelMarket.getApiFederateUrl())) {
            marketExecuteFederateResult.setCallUrl(channelMarket.getLink());
            return marketExecuteFederateResult;
        }

        //  获取联登包装类
        MarketFederateWrapper federateWrapper = marketFederateWrapperContext.getContext(channelMarket.getApiFederateType());
        MarketFederate marketFederate = MarketFederate.of(channelUserRegisterPO, listUserForm);
        ApiUserRequest apiUserRequest = federateWrapper.wrap(marketFederate);
        apiUserRequest.setReqId(ClassConvertUtils.toStr(marketExecuteTask.getReqId()));

        //  发起联登请求
        ApiHttpMessage apiHttpMessage = apiConsumerMarketHttpHandler.sendFederate(channelMarket, apiUserRequest, marketExecuteTask.getHttpTimeout());
        marketExecuteFederateResult.setHasSuc(apiHttpMessage.hasSuc());

        //  如果返回成功-获取回调地址
        if (apiHttpMessage.hasSuc()) {
            String responseBody = apiHttpMessage.getResponseBody();
            String url = JsonUtils.getNode(responseBody, "url");
            String callUrl = JsonUtils.getNode(responseBody, "callUrl");

            if (ValidParam.isNotEmpty(callUrl)) {
                marketExecuteFederateResult.setCallUrl(callUrl);
            } else {
                marketExecuteFederateResult.setCallUrl(url);
            }
        }
        return marketExecuteFederateResult;
    }
}
